#include "streamrecordercontroller.h"
#include "libs/base/basetype.h"
#include "streamrecorder.h"

StreamRecorderController::StreamRecorderController(int id, QObject* parent)
    : QObject { parent }, id_(id)
{
}

StreamRecorderController::~StreamRecorderController()
{
    if (thread_.isRunning()) {
        if (stream_recorder_) {
            disconnect(stream_recorder_, nullptr, this, nullptr);
            stream_recorder_->deleteLater();
            stream_recorder_ = nullptr;
        }
        thread_.quit();
        thread_.wait();
    }
}

bool StreamRecorderController::isRunning() const
{
    return (thread_.isRunning() && stream_recorder_->isRunning());
}

void StreamRecorderController::start(const StreamRecorderConfig& config)
{
    if (thread_.isRunning()) {
        if (stream_recorder_) {
            stream_recorder_->setConfig(config);
        }
        Q_EMIT startRequested(QPrivateSignal());
    } else {
        auto recorder = new StreamRecorder(config, nullptr);
        stream_recorder_ = recorder;
        recorder->moveToThread(&thread_);
        connect(recorder, &StreamRecorder::positionChanged, this,
                &StreamRecorderController::positionChanged);
        connect(recorder, &StreamRecorder::qosMetrics, this, &StreamRecorderController::qosMetrics);
        connect(recorder, &StreamRecorder::finished, this, &StreamRecorderController::finished);
        connect(recorder, &StreamRecorder::errorOccurred, this,
                &StreamRecorderController::errorOccurred);
        connect(this, &StreamRecorderController::startRequested, recorder, &StreamRecorder::start);
        connect(this, &StreamRecorderController::stopRequested, recorder, &StreamRecorder::stop);
        connect(this, &StreamRecorderController::terminateRequested, recorder,
                &StreamRecorder::terminate);
        thread_.start();
        Q_EMIT startRequested(QPrivateSignal());
    }
}

void StreamRecorderController::stop()
{
    if (isRunning()) {
        Q_EMIT stopRequested(QPrivateSignal());
    } else {
        Q_EMIT errorOccurred(yc::LOGIC_ERROR, tr("Not running."));
    }
}

void StreamRecorderController::terminate()
{
    if (isRunning()) {
        Q_EMIT terminateRequested(QPrivateSignal());
    } else {
        Q_EMIT errorOccurred(yc::LOGIC_ERROR, tr("Not running."));
    }
}
